import { getDiaryList, getWeeklyList } from '../../models/diary'
import { showToast } from '../../utils/util'

const defaultAvatarUrl = 'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0'

interface UserInfo {
  avatarUrl: string;
  nickName: string;
}

Page({
  data: {
    userInfo: {
      avatarUrl: defaultAvatarUrl,
      nickName: '',
    } as UserInfo,
    hasUserInfo: false,
    diaryCount: 0,
    weeklyCount: 0,
    daysCount: 0
  },
  onLoad() {
    this.loadUserInfo()
    this.loadStatistics()
  },
  onShow() {
    this.loadStatistics()
  },
  // 加载用户信息
  loadUserInfo() {
    try {
      const userInfo = wx.getStorageSync('userInfo')
      if (userInfo) {
        this.setData({
          userInfo,
          hasUserInfo: true
        })
      }
    } catch (e) {
      console.error('获取用户信息失败', e)
    }
  },
  
  // 加载统计数据
  loadStatistics() {
    const diaryList = getDiaryList()
    const weeklyList = getWeeklyList()
    
    // 统计不同天数的记录
    const uniqueDates = new Set<string>()
    diaryList.forEach(diary => {
      const date = new Date(diary.timestamp).toDateString()
      uniqueDates.add(date)
    })
    
    this.setData({
      diaryCount: diaryList.length,
      weeklyCount: weeklyList.length,
      daysCount: uniqueDates.size
    })
  },
  
  // 头像选择
  onChooseAvatar(e: any) {
    const { avatarUrl } = e.detail
    const { nickName } = this.data.userInfo
    const userInfo: UserInfo = {
      avatarUrl,
      nickName
    }
    
    this.setData({
      "userInfo.avatarUrl": avatarUrl,
      hasUserInfo: nickName && avatarUrl && avatarUrl !== defaultAvatarUrl
    })
    
    wx.setStorageSync('userInfo', userInfo)
  },
  
  // 昵称输入
  onInputChange(e: any) {
    const nickName = e.detail.value
    const { avatarUrl } = this.data.userInfo
    const userInfo: UserInfo = {
      avatarUrl,
      nickName
    }
    
    this.setData({
      "userInfo.nickName": nickName,
      hasUserInfo: nickName && avatarUrl && avatarUrl !== defaultAvatarUrl
    })
    
    wx.setStorageSync('userInfo', userInfo)
  },
  
  // 关于应用
  showAbout() {
    wx.showModal({
      title: '关于梦迹日记',
      content: '梦迹日记 v1.0.0\n\n"生活中的点滴，化作梦的痕迹。梦迹日记记录你的碎片时光，每周生成独特小故事，与好友分享。"\n\n感谢使用梦迹日记！',
      showCancel: false
    })
  },
  
  // 意见反馈
  showFeedback() {
    wx.showModal({
      title: '意见反馈',
      content: '如有问题或建议，请联系开发者邮箱：\nfeedback@dreamdiary.com',
      showCancel: false
    })
  },
  
  // 清空数据
  clearData() {
    wx.showModal({
      title: '清空数据',
      content: '确定要清空所有日记和周记数据吗？此操作不可恢复。',
      success: (res) => {
        if (res.confirm) {
          try {
            wx.removeStorageSync('diaryList')
            wx.removeStorageSync('weeklyList')
            showToast('数据已清空', 'success')
            this.loadStatistics()
          } catch (e) {
            console.error('清空数据失败', e)
            showToast('操作失败，请重试', 'error')
          }
        }
      }
    })
  }
}) 